﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;
using umbraco.interfaces;
using umbraco.cms.businesslogic.datatype;
using umbraco.uicontrols.TreePicker;
using umbraco;
using umbraco.IO;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using umbraco.presentation;
using System.Xml;

namespace TheOutfield.UmbExt.UniversalMediaPicker
{
    public class UniversalMediaPickerDataEditor : BaseTreePicker, IDataEditor
    {
        private UniversalMediaPickerDataType dataType;

        private string savedValue;

        public UniversalMediaPickerDataEditor(UniversalMediaPickerDataType dataType)
        {
            this.dataType = dataType;

            this.ModalWidth = 530;
            this.ModalHeight = 565;
        }

        public string SavedValue
        {
            get
            {
                if(string.IsNullOrEmpty(savedValue) && this.dataType.Data.Value != null)
                {
                    try
                    {
                        var xd = new XmlDocument();
                        xd.LoadXml(this.dataType.Data.Value.ToString());

                        var doc = xd.DocumentElement;
                        if (doc != null)
                        {
                            var dtdid = doc.Attributes["dataTypeId"] != null ? doc.Attributes["dataTypeId"].Value : "";
                            var valNode = doc.InnerText;

                            if (valNode != "" && dtdid == this.dataType.DataTypeDefinitionId.ToString())
                                savedValue = valNode;
                        }
                    }
                    catch (XmlException ex)
                    { }
                }

                return savedValue;
            }
        }

        public Control Editor
        {
            get { return this; }
        }

        public void Save()
        {
            var value = base.ItemIdValue.Value.Trim();

            var beforeSaveEventArgs = new BeforeSaveEventArgs(this.dataType.DataTypeDefinitionId, SavedValue, value);
            ((UniversalMediaPickerData)this.dataType.Data).InvokeBeforeSave(beforeSaveEventArgs);
            if (beforeSaveEventArgs.Cancel) return;

            var xd = new XmlDocument();
            xd.AppendChild(xmlHelper.addCDataNode(xd, "value", value));
            xd.DocumentElement.Attributes.Append(xmlHelper.addAttribute(xd, "dataTypeId", this.dataType.DataTypeDefinitionId.ToString()));

            this.dataType.Data.Value = xd.InnerXml;

            var afterSaveEventArs = new AfterSaveEventArgs(this.dataType.DataTypeDefinitionId, value);
            ((UniversalMediaPickerData)this.dataType.Data).InvokeAfterSave(afterSaveEventArs);
        }

        public bool ShowLabel 
        {
            get { return true; }
        }

        public bool TreatAsRichTextEditor
        {
            get { return false; }
        }

        public override string ModalWindowTitle
        {
            get { return (ui.GetText("general", "choose") + " " + ui.GetText("sections", "media")); }
        }

        protected override string GetItemTitle()
        {
            if (!string.IsNullOrEmpty(this.ItemIdValue.Value))
            {
                var provider = UniversalMediaPickerProviderFactory.GetProvider(dataType.DataTypeDefinitionId);

                var mi = UniversalMediaPickerCache.Get<MediaItem>(dataType.DataTypeDefinitionId + "$GetMediaItemById$" + this.ItemIdValue.Value);
                if (mi == null)
                {
                    mi = provider.GetMediaItemById(this.ItemIdValue.Value);
                    if(mi != null)
                        UniversalMediaPickerCache.Set(dataType.DataTypeDefinitionId + "$GetMediaItemById$" + this.ItemIdValue.Value, mi, DateTime.Now.AddSeconds(dataType.Config.CacheDuration));
                }

                return mi != null ? mi.Title : "ERROR! Unable to retreive media item";
            }

            return "";
        }

        public override string TreePickerUrl
        {
            get { return IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/plugins/theoutfield/universalmediapicker/universalmediapicker.aspx?dtdid=" + dataType.DataTypeDefinitionId; }
        }

        protected override string GetJSScript()
        {
            return string.Format("\r\n                var mc_{0} = new TheOutfield.UmbExt.UniversalMediaPicker.Controls.UniversalMediaPicker('{1}','{2}','{3}','{4}',{5},{6},'{7}');", 
                this.ClientID, 
                this.ModalWindowTitle, 
                base.ItemIdValue.ClientID, 
                base.ItemTitle.ClientID, 
                this.TreePickerUrl, 
                base.ModalWidth.ToString(), 
                base.ModalHeight.ToString(), 
                IOHelper.ResolveUrl(SystemDirectories.Umbraco).TrimEnd('/'));
        }

        protected override void RenderJSComponents()
        {
            base.RenderJSComponents();

            ScriptManager.RegisterClientScriptResource(this, typeof(UniversalMediaPickerDataType), "TheOutfield.UmbExt.UniversalMediaPicker.Scripts.JSON.js");
            ScriptManager.RegisterClientScriptResource(this, typeof(UniversalMediaPickerDataType), "TheOutfield.UmbExt.UniversalMediaPicker.Scripts.UniversalMediaPickerScripts.js");
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!((!ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack || !UmbracoContext.Current.LiveEditingContext.Enabled) && this.Page.IsPostBack))
            {
                base.ItemIdValue.Value = SavedValue;
            }
        }
    }
}